package com.bawei.hgshop.service.impl;

import java.util.List;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import com.bawei.hgshop.entity.Spec;
import com.bawei.hgshop.entity.SpecOption;
import com.bawei.hgshop.mapper.SpecMapper;
import com.bawei.hgshop.service.SpecService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service(interfaceClass = SpecService.class)
public class SpecServiceImpl implements SpecService {
	
	@Autowired
	SpecMapper specMapper;

	@Override
	public int add(Spec spec) {
		// TODO Auto-generated method stub
		//添加主表
		int n = specMapper.add(spec);
		
		//在添加子表
		spec.getOptions().forEach(x->{
			// 设置外键
			x.setSpecId(spec.getId());
			//插入子表
			specMapper.addOptions(x);
		});
		return n;
	}

	@Override
	public int update(Spec spec) {
		// TODO Auto-generated method stub
		
		//直接修改主表的数据
		int  n =  specMapper.update(spec);
		//处理子表
		spec.getOptions().forEach(x->{
			//原来存在的数据
			if(x.getId()>0) {
				//修改子表
				specMapper.updateOptions(x);
			}else {
				// 新增加的规格选项 加入到数据库当中
				// 设置外键
				x.setSpecId(spec.getId());
				specMapper.addOptions(x);
			}
		});
		
		return n;
	}

	@Override
	public int delBatch(int[] ids) {
		// TODO Auto-generated method stub
		//先删除子表
		int n = specMapper.delOptions(ids);
		//再删除主表
		specMapper.del(ids);
		return n;
	}
	
	@Override
	public PageInfo<Spec> list(int page,int pageSize) {
		// TODO Auto-generated method stub
		PageHelper.startPage(page, pageSize);
		return new PageInfo<Spec>(specMapper.list());
	}

	@Override
	public Spec findById(int id) {
		// TODO Auto-generated methsod stub
		return specMapper.findById(id);
	}

	@Override
	public int delOption(int id) {
		// TODO Auto-generated method stub
		return specMapper.delOptionById(id);
	}

	@Override
	public List<Spec> listAll() {
		// TODO Auto-generated method stub
		return specMapper.listAll();
	}

	@Override
	public List<SpecOption> listOptionsBySpecId(int specId) {
		// TODO Auto-generated method stub
		return specMapper.listOptionsBySpecId(specId);
	}

	@Override
	public List<Spec> listBySpuId(int spuId) {
		// TODO Auto-generated method stub
		return specMapper.listBySpuId(spuId);
	}

}
